<template>
  <div class="bg-black">
    <el-row>
      <el-col :span="4">
        <div v-for="(o, i) in APIlist" :key="o" class="my-2 px-2">
          <el-tooltip class="box-item" effect="dark" :content="o.url" placement="top-start">
            <el-alert :title="o.url" type="success" :closable="false" @click="getdata(o)" v-if="o.method == 'GET'" />
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" :content="o.url" placement="top-start">
            <el-alert :title="o.url" type="warning" :closable="false" @click="getdata(o)" v-if="o.method == 'POST'" />
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" :content="o.url" placement="top-start">
            <el-alert :title="o.url" type="error" :closable="false" @click="getdata(o)" v-if="o.method == 'DELETE'" />
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" :content="o.url" placement="top-start">
            <el-alert :title="o.url" type="info" :closable="false" @click="getdata(o)" v-if="o.method == 'PUT'" />
          </el-tooltip>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="mt-4">
          <el-input v-model="input3" type="url" placeholder="输入 API URL" class="input-with-select">
            <template #prepend>
              <el-select v-model="method" placeholder="Select" style="width: 115px">
                <el-option label="GET" value="get" />
                <el-option label="POST" value="post" />
                <el-option label="PUT" value="put" />
                <el-option label="DELETE" value="delete" />
              </el-select>
            </template>
            <template #append>
              <el-button icon="Promotion" type="primary" class="text-white" @click="APItest()">发送</el-button>
            </template>
          </el-input>
        </div>

        <el-row :gutter="10">
          <el-col :span="12">
            <div class="mt-4 text-left" style="position: relative">
              <el-tag type="warning" class="absolute top-0 left-0" style="z-index: 9999">请求头</el-tag>
              <!-- <json-editor-vue class="editor" v-model="body"  @blur="remarkValidate"/> -->
              <CodingEditor v-model="header" language="json" class="text-left" height="150px" />
            </div>
          </el-col>
          <el-col :span="12">
            <div class="mt-4 text-left" style="position: relative">
              <el-tag class="absolute top-0 left-0" style="z-index: 9999">参数</el-tag>
              <!-- <json-editor-vue class="editor" v-model="body"  @blur="remarkValidate"/> -->
              <CodingEditor v-model="body" language="json" class="text-left" height="150px" />
            </div>
          </el-col>
        </el-row>

        <div class="mt-4 text-left" style="position: relative; height: 400px; overflow: auto">
          <el-tag type="success" class="absolute top-0 left-0" style="z-index: 9999">{{ statusCode }}</el-tag>
          <!-- <json-editor-vue class="editor" v-model="body"  @blur="remarkValidate"/> -->
          <CodingEditor v-model="jsonData" language="json" class="text-left" height="450px" />
        </div>
        <div class="mt-4 text-left" style="position: relative">
          <el-input v-model="textarea" :rows="2" type="textarea" placeholder="Please input" />
          <el-button class="absolute bottom-0 right-0" @click="ai()">生成代码</el-button>
        </div>
        <div class="mt-4 text-left" style="position: relative">
          <div id="vditor" ref="vditor"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import CodingEditor from './components/code.vue';
// 1.1 引入Vditor 构造函数
import Vditor from 'vditor';
// 1.2 引入样式
import 'vditor/dist/index.css';
import { ref, reactive, toRefs, onMounted } from 'vue';
const { proxy } = getCurrentInstance();
const input3 = ref('');
const statusCode = ref('状态码');
const method = ref('get');
const body = ref({});
const header = ref({});
const jsonData = ref({});
var APIlist = ref([]);
const config = ref({});
const textarea = ref('生成JavaScript代码用axios，封装一个方法完成请求返回结果');
var codefx = ref('');
const qmessages = ref([
  {
    role: 'system',
    content:
      '\nYou are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2023-04\nCurrent model: gpt-4-all\nCurrent time: 2024/1/14 21:51:51\nLatex inline: $x^2$ \nLatex block: $$e=mc^2$$\n\n',
  },
]);
function ai() {
  codefx.value = '';
  retgpt(
    '用' +
      method.value +
      '方式，请求' +
      input3.value +
      'headers为' +
      header.value +
      '参数为' +
      body.value +
      textarea.value,
    codefx,
  );
}
async function APItest() {
  //http://119.45.240.39:4004/api/td

  console.log('data', body.value);
  var data = Object.keys(body.value).length === 0 ? {} : JSON.parse(escapeDoubleQuotes(body.value));
  var headers = Object.keys(header.value).length === 0 ? {} : JSON.parse(escapeDoubleQuotes(header.value));
  console.log('data', body.value);
  config.value = {
    method: method.value.toUpperCase(),
    url: input3.value,
    headers: headers,
    data: data,
  };
  APIlist.value.push(config.value);
  const result = await proxy.$ax.post('/4004/proxy', config.value);

  localStorage.setItem('APIlist', JSON.stringify(APIlist.value));
  jsonData.value = JSON.stringify(result.data);
  statusCode.value = '状态：' + result.statusCode + '=>用时：' + result.responseTime + 'ms';
  console.log('result', result);
}
function getType(value) {
  return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
function escapeDoubleQuotes(str) {
  return str.replace(/\n/g, '').replace(/ /g, '');
}
function getdata(o) {
  input3.value = o.url;
  method.value = o.method;
  body.value = JSON.stringify(o.data);
  header.value = JSON.stringify(o.headers);
}
async function retgpt(s, r) {
  qmessages.value.push({
    role: 'user',
    content: s,
  });
  const response = await fetch('/yzam/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer sk-Wza31MksVicYvfMjDLEAMcCP1S3htPXNrB6LYE5peSxB5mWp`,
      'Content-Type': 'application/json',
      // 其他需要的头部信息
    },
    body: JSON.stringify({
      messages: qmessages.value,
      model: 'moonshot-v1-8k',
      // presence_penalty: 0,
      stream: true,

      top_p: 1,
      temperature: 0.3,
      presence_penalty: 0.6,
      frequency_penalty: 0,
      // session_id: new Date()
    }),
  });
  console.log('response', response);
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  let currentMessage = '';
  qmessages.value.push({
    role: 'assistant',
    content: currentMessage,
  });
  // console.log(response)
  const reader = response.body.getReader();
  while (true) {
    const { value, done } = await reader.read();

    if (done) {
      console.log('done.');
      // console.log(list);
      console.log('done', r.value);
      loading.value = false;

      break; // 读取完毕
    } else {
      const dataText = new TextDecoder().decode(value);
      const data = dataText.split('\n\n').filter(Boolean);
      // console.log('message: ', new TextDecoder().decode(value));
      // console.log(data);
      // console.log('list', list)
      data.forEach(function (element) {
        // console.log('element', element)
        if (element.startsWith('data: ') && !element.includes('[DONE]')) {
          try {
            const line = JSON.parse(element.replace('data: ', ''));
            // console.log('line', line)
            if (
              line.choices[0].delta.role != 'assistant' &&
              line.choices[0].delta.content != null &&
              line.choices[0].delta.content != ''
            ) {
              currentMessage += line.choices[0].delta.content;
              // console.log('currentMessage', currentMessage)
              r.value = currentMessage;
              contentEditor.value.setValue(codefx.value);
            }
          } catch (error) {
            console.error('JSON parsing error:', error);
          }
        }
      });

      // list.forEach(function (element) {
      //     if (element.choices[0].delta.role != "assistant" && element.choices[0].delta.content != null) {
      //         that.currentMessage += element.choices[0].delta.content;
      //     }

      // });
      // console.log(that.currentMessage);

      // var data = new TextDecoder().decode(value);
      // this.messages.push(data.data.choices[0].delta.content);
    }
  }
}
const contentEditor = ref('');
onMounted(async () => {
  //  #读取localStorage APIlist 赋给 APIlist
  // #如果APIlist 存在则赋值
  if (localStorage.getItem('APIlist')) {
    APIlist.value = JSON.parse(localStorage.getItem('APIlist'));
    //     input3.value = APIlist.value[APIlist.value.length - 1].url;
    //     method.value = APIlist.value[APIlist.value.length - 1].method;
    //     body.value = APIlist.value[APIlist.value.length- 1].data;
  }
  // APIlist.value = JSON.parse(localStorage.getItem('APIlist'));
  //   if (APIlist.value) {
  //     input3.value = APIlist.value[APIlist.value.length - 1].url;
  //     method.value = APIlist.value[APIlist.value.length - 1].method;
  //     body.value = APIlist.value[APIlist.value.length - 1].data;
  //     header.value = APIlist.value[APIlist.value.length - 1].headers;
  // }
  contentEditor.value = new Vditor('vditor', {
    height: 360,
    theme: 'dark',
    toolbarConfig: {
      pin: true,
    },
    cache: {
      enable: false,
    },
    after: () => {
      contentEditor.value.setValue(codefx.value);
    },
  });
});
</script>
<style scoped lang="less"></style>
